import { reactive, computed } from 'vue'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/user'
import { type UserInfo } from '@/types/user'

interface UserState {
  token: string
  userInfo: UserInfo
}

const defaultUserInfo: UserInfo = {
  username: '',
  avatar: '',
}

// 创建响应式状态
const state = reactive<UserState>({
  token: getToken() || '',
  userInfo: { ...defaultUserInfo },
})

// Getter 等价物 - 使用 computed
const getTokenValue = computed(() => state.token)
const getUserInfoData = computed(() => state.userInfo)

// Actions
export function useUserStore() {
  const setUserToken = (token: string) => {
    setToken(token)
    state.token = token
  }

  const fetchUserInfo = (): Promise<UserInfo> => {
    return new Promise((resolve, reject) => {
      getUserInfo(state.token)
        .then((response) => {
          const { data } = response
          if (data) {
            state.userInfo = data || { ...defaultUserInfo }
            resolve(data)
          } else {
            reject('无数据')
          }
        })
        .catch((error) => {
          reject(error)
        })
    })
  }

  const resetToken = (): string => {
    removeToken()
    state.token = ''
    state.userInfo = { ...defaultUserInfo }
    return ''
  }

  // 提供状态和方法的访问
  return {
    // 状态
    state,

    // Getter 等价物
    token: getTokenValue,
    userInfo: getUserInfoData,

    // Actions
    setToken: setUserToken,
    getUserInfo: fetchUserInfo,
    resetToken,
  }
}

// 可选：创建全局单例
let userStoreInstance: ReturnType<typeof useUserStore> | null = null

export function getUserStore() {
  if (!userStoreInstance) {
    userStoreInstance = useUserStore()
  }
  return userStoreInstance
}
